package com.BookmanageSystem.controller;

import com.BookmanageSystem.entity.User;
import com.BookmanageSystem.service.UserService;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.midi.Soundbank;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    //登录功能
    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response,Model model) throws ServletException, IOException {
        System.out.println(request.getParameter("username"));
        User user=new User();
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        User user1=userService.login(user);
        if(user1!=null){
            HttpSession session=request.getSession();
            session.setAttribute("user",user.getUsername());
            request.setAttribute("roel",user1.getRoel());
            session.setAttribute("roel",user1.getRoel());
            System.out.println(user1.getRoel());
            return "tsgl";
        }else {
            request.setAttribute("loginstate", "用户名或密码错误");
            return "login";
        }
    }

    //注册
    @RequestMapping("/register")
    public String register(HttpServletRequest request){
        User user=new User();
        user.setUsername(request.getParameter("userName"));
        user.setPassword(request.getParameter("password1"));
        user.setRoel(0);
        Integer i=userService.register(user);
        return "login";
    }

    //验证账号
    @RequestMapping("/yzUserName")
    @ResponseBody
    public Integer yzUserName(HttpServletRequest request){
        User user=userService.getUserByName(request.getParameter("userName"));
        if(user!=null){
            return 0;
        }else{
            return 1;
        }
    }

    //到登录界面
    @RequestMapping("/tologin")
    public String tologin() {
        return "login";
    }

    @RequestMapping("/toregister")
    public String toregister(){
        return "register";
    }
}
